#include "mainwindow.h"
#include "ui_mainwindow.h"

#include <QVBoxLayout>
#include <QKeyEvent>
#include <QFile>

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent), ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    source = new Phonon::MediaObject(this);
    connect(source, SIGNAL(stateChanged(Phonon::State,Phonon::State)),
            SLOT(stateChanged(Phonon::State,Phonon::State)));
    connect(source, SIGNAL(bufferStatus(int)), this, SLOT(bufferStatus(int)));
    connect(source, SIGNAL(metaDataChanged()), this, SLOT(mediaMetaDataChanged()));

    audio = new Phonon::AudioOutput(Phonon::VideoCategory, this);
    video = new Phonon::VideoWidget(this);
    Phonon::createPath(source, audio);
    Phonon::createPath(source, video);

    /*QVBoxLayout* layout = new QVBoxLayout;
    layout->addWidget(video);
    setLayout(layout);*/
    this->setCentralWidget(video);
}

MainWindow::~MainWindow()
{
//    delete stream;
    delete ui;
}

/*void MainWindow::connectAuthenticator(QObject* receiver, const char* method)
{
    qDebug() << "Authentication";
    connect(&http, SIGNAL(authenticationRequired(QNetworkReply*, QAuthenticator*)),
            receiver, method);
}

bool MainWindow::canPlay(const QString& mimeType)
{
    return Phonon::BackendCapabilities::isMimeTypeAvailable(mimeType);
}
*/

void MainWindow::play()
{
/*    if (stream) {
        stream->close();
        stream->deleteLater(); // drop the old response
        stream = 0;
    }
*/
    //qDebug() << "PLAYING " << url.toString();

    loaded = false;
  /*  stream = http.get(QNetworkRequest(url));
//    stream->setReadBufferSize(HTTP_BUFFER_SIZE); // unlimited buffer
    connect(stream, SIGNAL(finished()), SLOT(httpFinished()));
    connect(stream, SIGNAL(metaDataChanged()), SLOT(httpMetaDataChanged()));
    connect(stream, SIGNAL(error(QNetworkReply::NetworkError)), SLOT(httpError(QNetworkReply::NetworkError)));
    connect(stream, SIGNAL(downloadProgress(qint64,qint64)), SLOT(httpProgress(qint64,qint64)));*/

//    stream = http.get(QNetworkRequest(QUrl("http://jjk.kapsi.fi/pub/pisara.mp4")));
//    connect(stream, SIGNAL(downloadProgress(qint64,qint64)), SLOT(httpProgress(qint64,qint64)));

    QFile* st = new QFile("/Users/jaakko/Projects/TVFeedView/test/pisara.mp4");
    source->setCurrentSource(st); //QUrl("http://foo:bar@jjk.kapsi.fi/pub/pw/pisara.mp4"));
    source->play();
}

/*void MainWindow::changeEvent(QEvent *e)
{
    QWidget::changeEvent(e);
    switch (e->type()) {
    case QEvent::LanguageChange:
        m_ui->retranslateUi(this);
        break;
    default:
        break;
    }
}*/

void MainWindow::keyPressEvent(QKeyEvent* event)
{
    switch (event->key()) {
    case Qt::Key_Space:
        play();
//        qDebug() << "State=" << source->state();
//        if (source->state() == Phonon::PlayingState)
//            source->pause();
//        else
//            source->play();
        return;
    }

    QWidget::keyPressEvent(event);
}

/*void MainWindow::httpFinished()
{
    QUrl url;
    switch (stream->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt()) {
        case 301:
        case 302:
        case 303:
            url = stream->attribute(QNetworkRequest::RedirectionTargetAttribute).toUrl();
            if (url.isEmpty())
                url = stream->header(QNetworkRequest::LocationHeader).toUrl();
            if (!url.isEmpty()) {
                qDebug() << "Redirected to " << url.toString();
                play(url);
            }
            break;

        case 200:
            source->setCurrentSource(stream);
            break;
    }
}*/

/*void MainWindow::httpMetaDataChanged()
{
//    qDebug() << "Response: " << stream->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt()
//             << " " << stream->attribute(QNetworkRequest::HttpReasonPhraseAttribute).toString();
//    qDebug() << "Redirect: " << stream->attribute(QNetworkRequest::RedirectionTargetAttribute).toString();
//    foreach (QByteArray h, stream->rawHeaderList())
//        qDebug() << h << ": " << stream->rawHeader(h);
}

void MainWindow::httpError(QNetworkReply::NetworkError code)
{
    qDebug() << "HTTP error " << code;
}*/

void MainWindow::httpProgress(qint64 cur, qint64 total)
{
    qDebug() << "Progress " << cur << "/" << total;
    if (!loaded && (cur > 16*1024)) {
        qDebug() << "Loading";
        source->setCurrentSource(stream);
//        player->load(Phonon::MediaSource(stream));
        loaded = true;
        source->setCurrentSource(stream); //QUrl("http://jjk.kapsi.fi/pub/pw/pisara.mp4"));
        source->play();

        // start playing after two seconds
        //QTimer::singleShot(2000, source, SLOT(play()));
    }
}

void MainWindow::stateChanged(Phonon::State cur, Phonon::State /*old*/)
{
    qDebug() << "State changed to " << cur; // << " error=" << stream->error();

    switch (cur) {
    case Phonon::LoadingState:
        qDebug() << "Loading...";
        break;
    case Phonon::StoppedState:
        qDebug() << "Stopped";
//        stream->abort();
//        stream->deleteLater();
        break;
    case Phonon::PlayingState:
        qDebug() << "Playing...";
        break;
    case Phonon::BufferingState:
        qDebug() << "Buffering...";
        break;
    case Phonon::PausedState:
        qDebug() << "Paused";
        break;
    case Phonon::ErrorState:
        qDebug() << "Error: " << source->errorString();
//        stream->abort();
//        stream->deleteLater();
        break;
    }
}

void MainWindow::bufferStatus(int percentFilled)
{
    qDebug() << "Buffer status: " << percentFilled;
}

void MainWindow::mediaMetaDataChanged()
{
    qDebug() << "Media metadata changed";
    QMultiMap<QString, QString> md = source->metaData();
    foreach (QString k, md.keys()) {
        qDebug() << k << ": " << md.values(k);
    }
}
